package com.zxl.yjb.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yjb.app.wxapi.WXPayEntryActivity;
import com.zxl.yjb.app.MyApplication;
import com.zxl.yjb.bean.WXOrderBean;
import com.zxl.yjb.bean.ZFBOrderBean;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.payfee.AuthResult;
import com.zxl.yjb.payfee.PayResult;

import java.util.Map;

public class PayFeeUtils {

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private Context context;
    //微信API
    private static IWXAPI api;

    private PayResulrListener payResulrListener;

    public PayFeeUtils(Context context)
    {
        this.context = context;
    }


    public static PayFeeUtils init(Context context)
    {
        PayFeeUtils payFeeUtils = new PayFeeUtils(context);
        api = WXAPIFactory.createWXAPI(context, MyApplication.WXAPPID);
        api.registerApp(MyApplication.WXAPPID);
        return payFeeUtils;
    }


    public interface PayResulrListener{
        void onResultSuccess();
        void onResulrFail();
    }

    public void addResulrListener(PayResulrListener payResulrListener)
    {
        this.payResulrListener = payResulrListener;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    Intent intent = new Intent(context, WXPayEntryActivity.class);
                    if (TextUtils.equals(resultStatus, "9000")) {
//                        Toast.makeText(PayFeeActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        intent.putExtra("payResult", "success");
                        context.startActivity(intent);
                        if (payResulrListener!=null)
                            payResulrListener.onResultSuccess();
                    } else {
//                        Toast.makeText(PayFeeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        intent.putExtra("payResult", "fail");
                        context.startActivity(intent);
                        if (payResulrListener!=null)
                            payResulrListener.onResulrFail();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        Toast.makeText(context,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        Toast.makeText(context,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    //开始调用支付宝支付
    public void alipay(Map<String, String> map) {
        DataManager dataManager = new DataManager();
        ObserverOnNextListener<ZFBOrderBean> listener = new ObserverOnNextListener<ZFBOrderBean>() {
            @Override
            public void onNext(ZFBOrderBean orderBean) {
                final String orderInfo = orderBean.getCredential().getAlipay().getOrderInfo();
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask((Activity) context);
                        Map<String, String> result = alipay.payV2(orderInfo, true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        };
        dataManager.payZFB(new ProgressObserver<ZFBOrderBean>(listener, context) {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                ToastUtils.show(context, "操作失败");
            }
        }, map);


    }

    /**
     * 微信支付
     *
     * @param map
     */
    public void wxPay(Map<String, String> map) {
        DataManager dataManager = new DataManager();
        ObserverOnNextListener<WXOrderBean> listener = new ObserverOnNextListener<WXOrderBean>() {
            @Override
            public void onNext(WXOrderBean wxOrderBean) {
                WXOrderBean.CredentialBean.WxBean wxPayBean = wxOrderBean.getCredential().getWx();
                PayReq req = new PayReq();
                req.appId = MyApplication.WXAPPID;//AppID
                req.partnerId = wxPayBean.getPartnerId();//商户号--
                req.prepayId = wxPayBean.getPrepayId();//预支付交易会话ID--
                req.nonceStr = wxPayBean.getNonceStr();//随机字符串--
                req.timeStamp = wxPayBean.getTimeStamp() + "";//时间戳--
                req.packageValue = wxPayBean.getPackageValue();//扩展字段
                req.sign = wxPayBean.getSign();//签名--
                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                api.sendReq(req);
            }
        };
        dataManager.payWX(new ProgressObserver<WXOrderBean>(listener, context) {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                ToastUtils.show(context, "操作失败");
            }
        }, map);

    }
}
